<template>
  <div class="dashboard-container">
    <div class="app-container">
      <el-card shadow="never">

        <el-row>
          <el-col :span="12"
            ><div class="grid-content bg-purple" style="color: pink">
              说明：目前支持学科和关键字条件筛选
            </div>
          </el-col>
          <el-col :span="12"
            ><div class="grid-content bg-purple add">
             <el-button  type="danger" size="small" @click="exportexec">excel导出</el-button>
              <el-button
                type="success"
                icon="el-icon-edit"
                style="background: #45be08; color: #fff" @click="addlist">新增试题</el-button>
            </div>
          </el-col>
        </el-row>

        <el-form
          class="demo-form-inline"
          :inline="true"
          :model="formdata"
          size="mini"
          label-width="68px"
          style="width: 100%"
          :label-position="labelPosition"
        >
          <el-row style="width: 100%">
            <el-col :span="6">
              <el-form-item label="学科">
              <el-select v-model="formdata.subjectID" placeholder="请选择" @change="subjectID(formdata.subjectID)">
                  <el-option
                    v-for="item in subjectList"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"

                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="二级目录">
                <el-select v-model="formdata.catalogID" placeholder="请选择">
                  <el-option v-for="item in catalogList" :key="item.id" :label="item.directoryName" :value="item.directoryName"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="标签">
                <el-select v-model="formdata.tags" placeholder="请选择">
                  <el-option v-for="item in tagsList" :key="item.id" :label="item.tagName" :value="item.tagName"></el-option>

                </el-select>
              </el-form-item>
            </el-col>
            <!-- style="width: 110%" -->
            <el-col :span="6">
              <el-form-item label="关键字">
                <el-input
                  v-model="formdata.keyword"
                  placeholder="根据题干搜索"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="6"
              ><el-form-item label="试题类型">
                <el-select v-model="formdata.difficulty" placeholder="请选择">
                  <el-option  v-for="item in difficultylist" :key="item.value" :label="item.label" :value="item.label"></el-option>

                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="难度">
                <el-select v-model="formdata.questionType" placeholder="请选择">
                  <el-option v-for="item in questionTypelist" :key="item.value" :label="item.label" :value="item.label"></el-option>

                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="方向">
                <el-select v-model="formdata.direction" placeholder="请选择">
                  <el-option v-for="(item,index) in directionlist" :key="index" :label="item" :value="item"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="录入人">
                <el-select v-model="formdata.creatorID" placeholder="请选择">
                  <el-option v-for="item in creatorIDlist" :key="item.id" :label="item.username" :value="item.username"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="6">
              <el-form-item label="题目备注">
                <el-input v-model="formdata.remarks"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="企业简称">
                <el-input
                  v-model="formdata.shortName"
                ></el-input> </el-form-item
            ></el-col>
            <el-col :span="6"
              >
              <el-form-item label="城市">
                <el-select
                  v-model="formdata.province"
                  placeholder="请选择"
                  style="width: 50%"
                  @change="getcity(formdata.province)"
                >
                  <el-option v-for="(item,index) in provincelist" :key="index" :label="item" :value="item"></el-option>
                </el-select>
                  <!-- @click.native="getcity(formdata.province)" -->
                <el-select
                  v-model="formdata.city"
                  placeholder="请选择"
                  style="width: 50%"
                  ref="sele"
                >
                  <el-option v-for="(item,index) in citylist" :key="index" :label="item" :value="item"></el-option>

                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <!-- -->
              <el-form-item style="padding-left: 30px">
                <el-button @click='cleans'>清除</el-button>
                <el-button type="primary" style="background:#409eff;color:#fff" @click="screen">搜索</el-button>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <el-alert :title="String(`数据一共 ${total} 条`)" type="info" :closable="false" show-icon>
        </el-alert>
        <!-- 表格列表 -->

        <el-table :data="tableData" style="width: 100%">
          <el-table-column prop="number" label="试题编号" width="180">
          </el-table-column>
          <el-table-column prop="subject" label="学科"> </el-table-column>
          <el-table-column prop="catalog" label="目录"> </el-table-column>

          <el-table-column prop="questionType" label="题型">
            <template #default="{ row }">
              {{ question(row.questionType) }}
            </template>
          </el-table-column>

          <el-table-column prop="question" label="题干" width="280">
            <template #default="{ row }">
              <span v-html="row.question"></span>
            </template>
          </el-table-column>
          <el-table-column prop="addDate" label="录入时间" width="160">
            <template #default="{ row }">
              {{ addtime(row.addDate) }}
            </template>
          </el-table-column>
          <el-table-column prop="difficulty" label="难度">
            <template #default="{ row }">
              {{ diff(row.difficulty) }}
            </template>
          </el-table-column>
          <el-table-column prop="creator" label="录入人"> </el-table-column>
          <el-table-column label="操作" width="180">
            <template #default="{ row }">
            <el-row>
              <el-button
                type="primary"
                plain
                icon="el-icon-view"
                circle
                @click="preview(row.id)"
              ></el-button>

              <el-button
                type="success"
                plain
                icon="el-icon-edit"
                circle
                @click='($router.push(`/questions/new?id=${row.id}`))'
                @open='revise(row.id)'
              ></el-button>
              <el-button
                type="danger"
                plain
                icon="el-icon-delete"
                circle
                @click="Delete(row.id)"
              ></el-button>
               <el-button
                type="warning"
                plain
                icon="el-icon-check"
                circle
                @click="collect(row)"
              >
              </el-button>
            </el-row>
             </template>
          </el-table-column>
        </el-table>
        <el-pagination
          background
          :page-sizes="[10, 20, 30, 40, 50]"
          layout="prev, pager, next ,sizes,jumper"
          :total="total"
          :page-size="pagesize"
          :current-page="page"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        >
        </el-pagination>
      </el-card>
      <questionsPreview :showRoleDialog.sync="showRoleDialog" :user-id='userId'/>
    </div>
  </div>
</template>

<script>
//
import { list as listdata, remove as removes, choiceAdd as choiceApi } from '@/api/hmmm/questions'
import { simple as simpledata } from '@/api/hmmm/subjects'
import { list as lists } from '@/api/hmmm/directorys'
import { list as listBQ } from '@/api/hmmm/tags'
import dayjs from 'dayjs'
import { difficulty, questionType, direction } from '@/api/hmmm/constants'
import { list as listss } from '@/api/base/users'

import { provinces as getprovinces, citys as getcitysApi } from '@/api/hmmm/citys'
import questionsPreview from '@/module-hmmm/components/questions-preview.vue'

export default {
  name: 'QuesTions',
  components: {
    questionsPreview
  },
  data () {
    return {
      showRoleDialog: false, // 控制预览弹窗的显示与影藏
      subjectList: [], // 学科
      catalogList: [], // 二级目录
      tagsList: [], // 标签
      questionTypelist: difficulty, // 试题类型
      difficultylist: questionType, // 难度
      directionlist: direction, // 方向
      creatorIDlist: [], // 录入人
      provincelist: [], // 市
      citylist: [], // 区
      labelPosition: 'right',
      tableData: [], // 列表数据
      page: 1, // 页码
      pagesize: 10, // 页容量
      total: 0, // 总数据条数
      userId: 0, // 预览 id
      formdata: {
        page: 1,
        pagesize: 10,
        subjectID: '', // 学科
        catalogID: '', // 目录
        tags: '', // 标签
        keyword: '', // 关键字
        questionType: '', // 试题类型
        difficulty: '', // 难度
        direction: '', // 方向
        creatorID: '', // 录入人
        remarks: '', // 题目备注
        shortName: '', // 企业简称
        province: '', // 所在省份
        city: '' // 所在城市

      }
    }
  },
  created () {
    this.createlistdata()
    this.createsimple()
    this.createlistss()
    this.getprovincesdata()
    // this.provincelist = getprovinces()
  },
  methods: {
    /**
     * 导出
     */
    async exportexec () {
      const { data: { items } } = await listdata(1, this.total)
      console.log(items)
      const headersArr = ['试题编号', '学科', '目录', '题型', '题干', '录入时间', '难度', '录入人']
      const headersRelations = {
        // eslint-disable-next-line quote-props
        '试题编号': 'number',
        // eslint-disable-next-line quote-props
        '学科': 'subject',
        // eslint-disable-next-line quote-props
        '目录': 'catalog',
        // eslint-disable-next-line quote-props
        '题型': 'questionType',
        // eslint-disable-next-line quote-props
        '题干': 'question',
        // eslint-disable-next-line quote-props
        '录入时间': 'addDate',
        // eslint-disable-next-line quote-props
        '难度': 'difficulty',
        // eslint-disable-next-line quote-props
        '录入人': 'creator'
      }

      const arr = this.formatDatas(items, headersArr, headersRelations)
      import('@/vendor/Export2Excel').then(excel => {
        excel.export_json_to_excel({
        // 导出表头
          header: headersArr,
          // 导出的数据
          data: arr,
          // 文件名
          filename: '员工信息',
          // 单元格宽度是否自适应
          autoWidth: true,
          // 文件后缀名
          bookType: 'xlsx'
        })
      })
    },
    formatDatas (items, headersArr, headersRelations) {
      const rulesArr = []
      items.forEach(item => {
        const tampArr = []
        headersArr.forEach(key => {
          const english = headersRelations[key]
          let value = item[english]
          if (['addDate'].includes(english)) {
            value = this.addtime(value)
          } else if (['difficulty'].includes(english)) {
            value = this.diff(value)
          } else if (['questionType'].includes(english)) {
            value = this.question(value)
          } else if (['question'].includes(english)) {
            const str1 = value.substring(3)
            const str2 = str1.replace('</p>', ' ')
            value = str2.replace('</p>', ' ')
          }
          tampArr.push(value)
        })
        rulesArr.push(tampArr)
      })
      return rulesArr
    },
    /**
     * 加入精选
     */
    collect (row) {
      this.$confirm('此操作将该题目加入精选, 是否继续?', '提示').then(async () => {
        await choiceApi({ id: row.id, choiceState: 1 })
        this.$message.success('加入精选成功')
        this.$router.push('/questions/choice')
      }).catch(() => {
      })
    },
    /**
     * 删除
     */
    async Delete (id) {
      this.$confirm('此操作将执行删除, 是否继续?', '提示').then(async () => {
        await removes({ id: id })
        // this.page = 1
        if (this.tableData.length === 1 && this.page > 1) {
          this.page--
        }
        this.$message.success('删除成功')
        this.createlistdata()
      }).catch(() => {

      })
    },
    /**
     * 显示预览弹窗
     */
    preview (id) {
      // console.log(1)
      this.showRoleDialog = true
      this.userId = id

      // console.log('aaaa', this.userId)
    },
    /**
     * 添加按钮
     */
    addlist () {
      this.$router.push('/questions/new')
    },
    /**
     * 搜索按钮
     */
    async screen () {
      if (this.formdata.subjectID !== '') {
        const { data } = await listdata({ subjectID: this.formdata.subjectID })
        this.tableData = data.items
        this.total = data.counts
      }
      if (this.formdata.keyword !== '') {
        const { data } = await listdata({ keyword: this.formdata.keyword })
        // console.log(data.items)
        // this.tableData = data.items
        // console.log(data)
        this.tableData = data.items
        // console.log(this.tableData)
        this.total = data.counts
        // console.log(this.total)
      } else if (this.formdata.subjectID !== '' && this.formdata.keyword !== '') {
        const { data } = await listdata({ subjectID: this.formdata.subjectID, keyword: this.formdata.keyword })
        this.tableData = data.items
        this.total = data.counts
      }
    },
    /**
     * 清除按钮
     */
    cleans () {
      this.formdata = {
        page: 1,
        pagesize: 10,
        subjectID: '', // 学科
        catalogID: '', // 目录
        tags: '', // 标签
        keyword: '', // 关键字
        questionType: '', // 试题类型
        difficulty: '', // 难度
        direction: '', // 方向
        creatorID: '', // 录入人
        remarks: '', // 题目备注
        shortName: '', // 企业简称
        province: '', // 所在省份
        city: '' // 所在城市

      }
      this.citylist = []
      this.createlistdata()
    },
    /**
     * 区数据
     */
    async getcity (pname) {
      const res = await getcitysApi(pname)
      console.log('aaa', res)
      this.citylist = res
      this.formdata.city = ''
    },
    /**
     * 市数据
     */
    async getprovincesdata () {
      const res = await getprovinces()
      console.log(res)
      this.provincelist = res
    },

    /**
     * 录入人数据
     */
    async createlistss () {
      const { data: { list } } = await listss()
      this.creatorIDlist = list
    },

    /**
     * 学科
     */
    async createsimple () {
      const { data } = await simpledata()

      // console.log(data)
      this.subjectList = data
      // console.log(this.subjectList)
      // console.log(data.label)
      // this.formdata.subjectID = data
      // console.log(this.formdata.subjectID)
    },
    async subjectID (id) {
      /**
       * 二级目录数据
       */
      this.formdata.catalogID = ''
      this.formdata.tags = ''
      const { data: { items } } = await lists({ id: id, page: 1, pagesize: 999 })

      this.catalogList = items.filter(item => item.id === id)

      /**
 * 标签数据
 */
      const { data: { items: itemsBQ } } = await listBQ({ id: id, page: 1, pagesize: 999 })

      this.tagsList = itemsBQ.filter(item => item.id === id)
    },
    /**
     * 列表时间处理
     */
    addtime (item) {
      return dayjs(item).format('YYYY-MM-DD')
    },
    /**
     * 难度数据处理
     */
    diff (item) {
      if (item === '1') {
        item = '简单'
      } else if (item === '2') {
        item = '一般'
      } else {
        item = '困难'
      }
      return item
      // console.log(item)
      // return item === '1' ? '简单' : '困难'
    },
    /**
     * 题型数据处理
     */
    question (item) {
      if (item === '1') {
        item = '单选'
      } else if (item === '2') {
        item = '多选'
      } else {
        item = '简单'
      }
      return item
    },
    handleSizeChange (val) {
      // console.log(val)
      // 当前页数据=val
      this.pagesize = val
      // console.log(this.pagesize)
      this.createlistdata()

      // console.log(`每页 ${val} 条`)
    },
    // 页码变化
    handleCurrentChange (val) {
      this.page = val
      this.createlistdata()

      // console.log(`当前页: ${val}`)
    },
    /**
     * 基础题库列表
     */
    async createlistdata () {
      const { data } = await listdata({
        page: this.page,
        pagesize: this.pagesize
      })

      this.tableData = data.items

      this.total = data.counts
      this.creatorIDlist = data.items[0].creator
    }
  }
}
</script >

<style scoped lang='scss'>
::v-deep .el-button--primary {
  color: #409eff;
  background: #ecf5ff;
  border-color: #b3d8ff;
}
::v-deep .el-button--success {
  color: #67c23a;
  background: #f0f9eb;
  border-color: #c2e7b0;
}
::v-deep .el-button--info {
  color: #f56c6c;
  background: #fef0f0;
  border-color: #fbc4c4;
}
::v-deep .el-button--danger {
  color: #e6a23c;
  background: #fdf6ec;
  border-color: #f5dab1;
}
::deep .grid-content {
  display: flex;
  align-items: flex-end;
}
::v-deep .el-form-item {
  margin-right: 0 !important;
  display: flex;
  justify-content: space-between;

}
::v-deep .el-form-item__label {
  position: absolute;
}
::v-deep .el-form-item__content {
  width: 92%;
  padding-left: 70px;
}
::v-deep .el-select,
.el-input_inner {
  width: 100%;
}

::v-deep .el-input--mini .el-input__inner {
  height: 33px;
  line-height: 32px;
}
::v-deep .el-button--mini {
  font-size: 19px;
}
::v-deep .el-button--medium {
  font-size: 12px;
}
::v-deep .el-row {
  margin-bottom: 20px;
}
::v-deep .el-pagination {
  // display: flex;
  // justify-content: right;
  margin-top: 10px;
}
::v-deep .el-button.is-circle {
  width: 33px;
  height: 33px;
}
::v-deep .cell {
  width: 180px !important;
  padding-right: 10px !important;
}
.add {
  transform: translate(60%);
}
</style>
